package com.example.carrierapp.net;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;

import com.example.carrierapp.config.ConstValue;
import com.example.carrierapp.net.listener.DataCallBackListener;
import com.example.carrierapp.ui.dialog.DialogUtils;
import com.example.carrierapp.util.ActivityUtil;
import com.example.carrierapp.util.AppUtil;
import com.example.carrierapp.util.LogUtil;
import com.example.carrierapp.util.SPUtils;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Subscription;

import io.reactivex.Flowable;
import io.reactivex.FlowableSubscriber;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 网络请求的中间件
 */
public class ApiMiddleHelper {
    private static ApiMiddleHelper mApiMiddleWare;
    private boolean mDialogShow;//标识dialog已经显示
    private Dialog mLoginDialog;

    public synchronized static ApiMiddleHelper getInstance() {
        if (mApiMiddleWare == null)
            mApiMiddleWare = new ApiMiddleHelper();
        return mApiMiddleWare;
    }


    /**
     * 访问服务器 子线程 返回到主线程
     *
     * @param flowable
     * @param listener
     */
    public void toNetIo2Main(Context context, Flowable<JsonObject> flowable, DataCallBackListener listener) {
        if (context != null && !AppUtil.isNetworkConnected(context) && listener != null) {
            listener.onFailure("请求数据超时，请检查您的网络连接");
            return;
        }
        flowable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new FlowableSubscriber<JsonObject>() {
            @Override
            public void onSubscribe(Subscription s) {
                s.request(Long.MAX_VALUE);
            }

            @Override
            public void onNext(JsonObject jsonObject) {
                JSONObject object = null;
                try {
                    if (!jugeLoginState(jsonObject.toString())) {
                        showDialog(context);
                        return;
                    }
                    object = new JSONObject(jsonObject.toString());
                    if (object.getBoolean("success")) {
                        String result = object.getString("result");
                        if (listener != null) {
                            listener.onSuccess(result);
                        }
                    } else {
                        JSONObject objectt = new JSONObject(object.getString("error"));
                        if (objectt!=null&&objectt.getString("message") != null) {
                            if (listener != null) {
                                listener.onFailure(objectt.getString("message"));
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.onFailure("服务器数据错误，请稍后再试。。。");
                    }
                }
            }

            @Override
            public void onError(Throwable t) {
                if (listener != null) {
                    listener.onFailure("服务器数据错误，请稍后再试。。。");
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private boolean jugeLoginState(String json) {
        boolean mLogin = true;
        try {
            LogUtil.d("jugeLoginState-1-" + json);
            JSONObject jsonObject = new JSONObject(json);
            boolean success = jsonObject.getBoolean("success");
            if (!success) {
                String error = jsonObject.getString("error");
                if(!TextUtils.isEmpty(error)&&!error.equals("null"))
                {
                    JSONObject errorJson = new JSONObject(error);
                    String msg = errorJson.getString("message");
                    return !msg.equals("Current user did not login to the application!");
                }else
                {
                    return false;
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mLogin;
    }

    private void showDialog(Context context) {
        if (context == null) {
            return;
        }
        SPUtils.putBoolean(context, ConstValue.LOGIN_STATE, false);
        if (mDialogShow) {
            return;
        }
        mLoginDialog = new DialogUtils.Builder(context)
                .setMessage("登录无效，请重新登录！")
                .setOutTouch(false)
                .setOnlyPositive()
                .setPositiveButton(null, null, v -> {
                    mLoginDialog.dismiss();
                    ActivityUtil.startLogin(context, false);
                }).creat();
        mLoginDialog.setOnDismissListener(dialog -> mDialogShow = false);
        if (mLoginDialog != null && !mLoginDialog.isShowing()) {
            mLoginDialog.show();
            mDialogShow = true;
        }
    }
}
